<template>
    <div>
        <div class="box">
            <el-card class="box_model">
                <div slot="header">
                    <span>模型分类</span>
                </div>
                <div>
                    <el-tree
                            :data="data"
                            default-expand-all
                            :props="{children: 'children',label: 'label'}"
                            :allow-drop="() => {return true;}">
                        <span class="custom-tree-node" slot-scope="{ node, data }">
                            <span draggable="true" @dragstart="dragstart">
                                <span v-if="data.children"><img src="/icons/folder.png" alt="" /> {{ data.label }}</span>
                                <span v-else><img src="/icons/file.png" alt="" /> {{ data.label }}</span>
                            </span>
                        </span>
                    </el-tree>
                </div>
            </el-card>
            <div class="box_content" id="myDiagramDiv" @dragover="allowDrop" @drop="dropend"></div>
            <div class="box_algorithm" id="myPaletteDiv">
                <el-tabs type="border-card">
                    <el-tab-pane>
                        <span slot="label"><i class="el-icon-date"></i> 我的行程</span>
                        我的行程
                    </el-tab-pane>
                    <el-tab-pane label="消息中心">消息中心</el-tab-pane>
                    <el-tab-pane label="角色管理">角色管理</el-tab-pane>
                    <el-tab-pane label="定时任务补偿">定时任务补偿</el-tab-pane>
                </el-tabs>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
    import {Component, Vue} from "vue-property-decorator";
    import '../../../../public/plugins/go'
    declare var go: any;

    @Component
    export default class GoJSModel extends Vue {

        private dragMoveText: string = '';
        private data: any = [
            {
                label: '一级 1',
                icon:'el-icon-folder',
                children: [{
                    label: '二级 1-1',
                    icon:'el-icon-folder',
                    children: [{
                        label: '三级 1-1-1',
                        icon:'el-icon-document'
                    }]
                }]
            }, {
                label: '一级 2',
                icon:'el-icon-folder',
                children: [{
                    label: '二级 2-1',
                    icon:'el-icon-folder',
                    children: [{
                        icon:'el-icon-document',
                        label: '三级 2-1-1'
                    }]
                }, {
                    label: '二级 2-2',
                    icon:'el-icon-folder',
                    children: [{
                        icon:'el-icon-document',
                        label: '三级 2-2-1'
                    }]
                }]
            }]

        private dragstart(ev: any): void {
            ev.dataTransfer.setData("Text",ev.target.innerText);
        }
        private allowDrop(ev: any): void{
            ev.preventDefault();
        }
        private dropend(ev: any): void {
            ev.preventDefault();
            this.dragMoveText=ev.dataTransfer.getData("Text");
        }

        public mounted() {

            const $ = go.GraphObject.make;  // for conciseness in defining templates

            const myDiagram =
                $(go.Diagram, "myDiagramDiv",  // must name or refer to the DIV HTML element
                    {
                        grid: $(go.Panel, "Grid",
                            $(go.Shape, "LineH", { stroke: "lightgray", strokeWidth: 0.5 }),
                            $(go.Shape, "LineH", { stroke: "gray", strokeWidth: 0.5, interval: 10 }),
                            $(go.Shape, "LineV", { stroke: "lightgray", strokeWidth: 0.5 }),
                            $(go.Shape, "LineV", { stroke: "gray", strokeWidth: 0.5, interval: 10 })
                        ),
                        allowDrop: true,  // must be true to accept drops from the Palette
                        "draggingTool.dragsLink": true,
                        "draggingTool.isGridSnapEnabled": true,
                        "linkingTool.isUnconnectedLinkValid": true,
                        "linkingTool.portGravity": 20,
                        "relinkingTool.isUnconnectedLinkValid": true,
                        "relinkingTool.portGravity": 20,
                        "relinkingTool.fromHandleArchetype":
                            $(go.Shape, "Diamond", { segmentIndex: 0, cursor: "pointer", desiredSize: new go.Size(8, 8), fill: "tomato", stroke: "darkred" }),
                        "relinkingTool.toHandleArchetype":
                            $(go.Shape, "Diamond", { segmentIndex: -1, cursor: "pointer", desiredSize: new go.Size(8, 8), fill: "darkred", stroke: "tomato" }),
                        "linkReshapingTool.handleArchetype":
                            $(go.Shape, "Diamond", { desiredSize: new go.Size(7, 7), fill: "lightblue", stroke: "deepskyblue" }),
                        "rotatingTool.snapAngleMultiple": 15,
                        "rotatingTool.snapAngleEpsilon": 15,
                        "undoManager.isEnabled": true
                    });

            const div = <HTMLElement>document.getElementById("myDiagramDiv")
            const PIXELRATIO = myDiagram.computePixelRatio()
            div.addEventListener("dragover", (event: any) => {
                event.preventDefault();
            }, false);
            div.addEventListener("drop", (event: any) => {
                event.preventDefault();
                if (div === myDiagram.div) {
                    const can = event.target;
                    // if the target is not the canvas, we may have trouble, so just quit:
                    if (!(can instanceof HTMLCanvasElement)) return;
                    const bbox = can.getBoundingClientRect();
                    let bbw = bbox.width;
                    if (bbw === 0) bbw = 0.001;
                    let bbh = bbox.height;
                    if (bbh === 0) bbh = 0.001;
                    const mx = event.clientX - bbox.left * ((can.width/PIXELRATIO) / bbw);
                    const my = event.clientY - bbox.top * ((can.height/PIXELRATIO) / bbh);
                    const point = myDiagram.transformViewToDoc(new go.Point(mx, my));
                    myDiagram.startTransaction('new node');
                    myDiagram.model.addNodeData({
                        location: point,
                        text: this.dragMoveText,
                        color: "lightyellow"
                    });
                    myDiagram.commitTransaction('new node');
                }
            }, false);


            const nodeSelectionAdornmentTemplate =
                $(go.Adornment, "Auto",
                    $(go.Shape, { fill: null, stroke: "deepskyblue", strokeWidth: 1.5, strokeDashArray: [4, 2] }),
                    $(go.Placeholder)
                );

            const nodeResizeAdornmentTemplate =
                $(go.Adornment, "Spot",
                    { locationSpot: go.Spot.Right },
                    $(go.Placeholder),
                    $(go.Shape, { alignment: go.Spot.TopLeft, cursor: "nw-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" }),
                    $(go.Shape, { alignment: go.Spot.Top, cursor: "n-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" }),
                    $(go.Shape, { alignment: go.Spot.TopRight, cursor: "ne-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" }),

                    $(go.Shape, { alignment: go.Spot.Left, cursor: "w-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" }),
                    $(go.Shape, { alignment: go.Spot.Right, cursor: "e-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" }),

                    $(go.Shape, { alignment: go.Spot.BottomLeft, cursor: "se-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" }),
                    $(go.Shape, { alignment: go.Spot.Bottom, cursor: "s-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" }),
                    $(go.Shape, { alignment: go.Spot.BottomRight, cursor: "sw-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" })
                );

            var nodeRotateAdornmentTemplate =
                $(go.Adornment,
                    { locationSpot: go.Spot.Center, locationObjectName: "CIRCLE" },
                    $(go.Shape, "Circle", { name: "CIRCLE", cursor: "pointer", desiredSize: new go.Size(7, 7), fill: "lightblue", stroke: "deepskyblue" }),
                    $(go.Shape, { geometryString: "M3.5 7 L3.5 30", isGeometryPositioned: true, stroke: "deepskyblue", strokeWidth: 1.5, strokeDashArray: [4, 2] })
                );

            myDiagram.nodeTemplate =
                $(go.Node, "Spot",
                    { locationSpot: go.Spot.Center },
                    new go.Binding('location'),
                    { selectable: true, selectionAdornmentTemplate: nodeSelectionAdornmentTemplate },
                    { resizable: true, resizeObjectName: "PANEL", resizeAdornmentTemplate: nodeResizeAdornmentTemplate },
                    new go.Binding("angle").makeTwoWay(),
                    // the main object is a Panel that surrounds a TextBlock with a Shape
                    $(go.Panel, "Auto",
                        { name: "PANEL" },
                        new go.Binding("desiredSize", "size", go.Size.parse).makeTwoWay(go.Size.stringify),
                        $(go.Shape, "Rectangle",  // default figure
                            {
                                portId: "", // the default port: if no spot on link data, use closest side
                                fromLinkable: true, toLinkable: true, cursor: "pointer",
                                fill: "#f39b77",  // default color
                                strokeWidth: 2
                            },
                            new go.Binding("figure"),
                            new go.Binding("fill")),
                        $(go.TextBlock,
                            {
                                font: "bold 11pt Helvetica, Arial, sans-serif",
                                margin: 18,
                                maxSize: new go.Size(160, NaN),
                                wrap: go.TextBlock.WrapFit,
                                editable: true
                            },
                            new go.Binding("text").makeTwoWay())
                    ),
                    // four small named ports, one on each side:
                    makePort("T", go.Spot.Top, false, true),
                    makePort("L", go.Spot.Left, true, true),
                    makePort("R", go.Spot.Right, true, true),
                    makePort("B", go.Spot.Bottom, true, false),
                    { // handle mouse enter/leave events to show/hide the ports
                        mouseEnter: function(e: any, node: any) { showSmallPorts(node, true); },
                        mouseLeave: function(e: any, node: any) { showSmallPorts(node, false); }
                    }
                );

            function makePort(name: any, spot: any, output: any, input: any) {
                // the port is basically just a small transparent square
                return $(go.Shape, "Circle",
                    {
                        fill: null,  // not seen, by default; set to a translucent gray by showSmallPorts, defined below
                        stroke: null,
                        desiredSize: new go.Size(7, 7),
                        alignment: spot,  // align the port on the main Shape
                        alignmentFocus: spot,  // just inside the Shape
                        portId: name,  // declare this object to be a "port"
                        fromSpot: spot, toSpot: spot,  // declare where links may connect at this port
                        fromLinkable: output, toLinkable: input,  // declare whether the user may draw links to/from here
                        cursor: "pointer"  // show a different cursor to indicate potential link point
                    });
            }

            function showSmallPorts(node: any, show: any) {
                node.ports.each(function(port: any) {
                    if (port.portId !== "") {  // don't change the default port, which is the big shape
                        port.fill = show ? "rgba(0,0,0,.3)" : null;
                    }
                });
            }

            const linkSelectionAdornmentTemplate =
                $(go.Adornment, "Link",
                    $(go.Shape,
                        // isPanelMain declares that this Shape shares the Link.geometry
                        { isPanelMain: true, fill: null, stroke: "deepskyblue", strokeWidth: 0 })  // use selection object's strokeWidth
                );

            myDiagram.linkTemplate =
                $(go.Link,  // the whole link panel
                    { selectable: true, selectionAdornmentTemplate: linkSelectionAdornmentTemplate },
                    { relinkableFrom: true, relinkableTo: true, reshapable: true },
                    {
                        routing: go.Link.AvoidsNodes,
                        curve: go.Link.JumpOver,
                        corner: 5,
                        toShortLength: 4
                    },
                    new go.Binding("points").makeTwoWay(),
                    $(go.Shape,  // the link path shape
                        { isPanelMain: true, strokeWidth: 2 }),
                    $(go.Shape,  // the arrowhead
                        { toArrow: "Standard", stroke: null }),
                    $(go.Panel, "Auto",
                        new go.Binding("visible", "isSelected").ofObject(),
                        $(go.Shape, "RoundedRectangle",  // the link shape
                            { fill: "#F8F8F8", stroke: null }),
                        $(go.TextBlock,
                            {
                                textAlign: "center",
                                font: "10pt helvetica, arial, sans-serif",
                                stroke: "#919191",
                                margin: 2,
                                minSize: new go.Size(10, NaN),
                                editable: true
                            },
                            new go.Binding("text").makeTwoWay())
                    )
                );

            const myPalette =
                $(go.Palette, "myPaletteDiv",  // must name or refer to the DIV HTML element
                    {
                        maxSelectionCount: 1,
                        nodeTemplateMap: myDiagram.nodeTemplateMap,  // share the templates used by myDiagram
                        linkTemplate: // simplify the link template, just in this Palette
                            $(go.Link,
                                { // because the GridLayout.alignment is Location and the nodes have locationSpot == Spot.Center,
                                    // to line up the Link in the same manner we have to pretend the Link has the same location spot
                                    locationSpot: go.Spot.Center,
                                    selectionAdornmentTemplate:
                                        $(go.Adornment, "Link",
                                            { locationSpot: go.Spot.Center },
                                            $(go.Shape,
                                                { isPanelMain: true, fill: null, stroke: "deepskyblue", strokeWidth: 0 }),
                                            $(go.Shape,  // the arrowhead
                                                { toArrow: "Standard", stroke: null })
                                        )
                                },
                                {
                                    routing: go.Link.AvoidsNodes,
                                    curve: go.Link.JumpOver,
                                    corner: 5,
                                    toShortLength: 4
                                },
                                new go.Binding("points"),
                                $(go.Shape,  // the link path shape
                                    { isPanelMain: true, strokeWidth: 2 }),
                                $(go.Shape,  // the arrowhead
                                    { toArrow: "Standard", stroke: null })
                            ),
                        model: new go.GraphLinksModel([  // specify the contents of the Palette
                            { text: "算法1", figure: "Diamond", fill: "lightskyblue" },
                            { text: "算法2", figure: "Diamond", fill: "lightskyblue" },
                            { text: "算法3", figure: "Diamond", fill: "lightskyblue" },
                            { text: "算法4", figure: "Diamond", fill: "lightskyblue" },
                            { text: "算法5", figure: "Diamond", fill: "lightskyblue" },
                            { text: "算法6", figure: "Diamond", fill: "lightskyblue" },
                            { text: "算法7", figure: "Diamond", fill: "lightskyblue" },
                            { text: "算法8", figure: "Diamond", fill: "lightskyblue" },
                            { text: "算法9", figure: "Diamond", fill: "lightskyblue" },
                        ])
                    });

            // setTimeout(() => {
            //     myPalette.model = new go.GraphLinksModel([
            //         { text: "算法4", figure: "Diamond", fill: "lightskyblue" },
            //         { text: "算法5", figure: "Diamond", fill: "lightskyblue" },
            //         { text: "算法6", figure: "Diamond", fill: "lightskyblue" }
            //     ])
            // }, 3000)

        }
    }
</script>

<style lang="scss">

    .box{
        width: 100%;
        display: flex;
        justify-content: space-between
    }
    .box_model{
        text-align: left;
        flex: 0 0 220px;
        margin-right: 5px;
    }
    .box_content{
        flex: 1;
        height: 600px;
        border: solid 1px #ccc
    }
    .box_algorithm{
        flex: 0 0 220px;
        margin-left: 5px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
    }
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
</style>
